<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

App::uses('ModelBehavior', 'Model');

class CodigoBehavior extends ModelBehavior {

    public function siguienteCodigo(&$model, $tipo) {
        if(empty($tipo) || !in_array($tipo, array(1, 2)))
            $tipo = 1;
        $solicitud = ($tipo == 1) ? 'ALQ-' : 'REP-';
        $dbo = $model->getDataSource();
        $dbo->execute('BEGIN WORK;');
        $dbo->execute(sprintf('LOCK TABLE %s IN SHARE MODE;', $model->table, $model->alias));
        $cantRegistros = $model->find('count', array('recursive' => -1, 'conditions' => array($model->alias . '.estatus >' => 0, $model->alias . '.tipo' => $tipo)));
        $data[$model->alias]['id'] = $model->getInsertID();
        $data[$model->alias]['codigo'] = $solicitud . str_pad($cantRegistros, 4, '0', STR_PAD_LEFT);
        $model->save($data);
        $dbo->execute('COMMIT;');
    }

}
